﻿using System;
#if WINDOWS
using System.Windows.Forms;
#endif
#if WINDOWS || SILVERLIGHT
using System.Windows.Threading;
#endif

namespace Narwhunderful.Aphelia.Framework
{

    public static class EventHandlerExtensions
    {

        public static void SafeInvoke<T>(this EventHandler<T> evt, object sender, T e) where T : EventArgs
        {
            if (evt != null) evt(sender, e);
        }

        public static void SafeCrossThreadInvoke<T>(this EventHandler<T> evt, object sender, T e) where T : EventArgs
        {
            if (evt != null)
            {
                object[] args = new object[] {sender, e};
                foreach (Delegate d in evt.GetInvocationList())
                {
#if WINDOWS // WINFORM
                    if (d.Target is Control)
                    {
                        Control c = (Control)d.Target;
                        if (c != null)
                        {
                            if (c.InvokeRequired)
                            {
                                c.BeginInvoke(d, args);
                                continue;
                            }
                        }
                    }
#endif
#if WINDOWS || SILVERLIGHT // WPF & Silverlight
                    if (d.Target is DispatcherObject)
                    {
                        DispatcherObject dispatcher = (DispatcherObject)d.Target;
                        if (dispatcher != null)
                        {
                            if (!dispatcher.CheckAccess())
                            {
                                dispatcher.Dispatcher.BeginInvoke(d, args);
                                continue;
                            }
                        }
                    }
#endif
                    d.DynamicInvoke(args);
                }
            }
        }

    }

}
